﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using Janus.Windows.Schedule;
using Janus.Windows.UI;
using Janus.Windows.UI.Dock;
using Janus.Windows.UI.CommandBars;

namespace YiLe.UI
{
    public partial class TestMainForm : Form
    {

        //public static readonly int ContactsImageIndex = 27;
        //public static readonly int CustomersImageIndex = 28;
        //public static readonly int SuppliersImageIndex = 29;
        //public static readonly int EmployeesImageIndex = 30;
        //public static readonly int CalendarImageIndex = 31;
        //public static readonly int ProductsAndOrdersImageIndex = 32;
        //public static readonly int ProductsImageIndex = 33;
        //public static readonly int OrdersImageIndex = 34;


        #region PanelManager events
        private void panelManager_GroupSelectedPanelChanged(object sender, Janus.Windows.UI.Dock.GroupSelectedPanelChangedEventArgs e)
        {
            if (!this.initialized)
            {
                return;
            }
            if (e.SelectedPanel == this.uipContacts)
            {
                OnContactsPanelSelected();
            }
            else if (e.SelectedPanel == this.uipProductsAndOrders)
            {
                this.OnProductsAndOrdersPanelSelected();
            }
            else if (e.SelectedPanel == this.uipCalendar)
            {
                this.OnCalendarPanelSelected();
            }

        }

        #endregion

        private bool selectFolder;
        private bool initialized;
        public void InitializeMainForm()
        {

            if (YiLeSystemApp.ReadSettingsFromDS)
            {
                this.StartPosition = FormStartPosition.Manual;
                this.Left = YiLeSystemApp.AppSettings.FormLeft;
                this.Top = YiLeSystemApp.AppSettings.FormTop;
                this.Width = YiLeSystemApp.AppSettings.FormWidth;
                this.Height = YiLeSystemApp.AppSettings.FormHeight;
                this.WindowState = (FormWindowState)YiLeSystemApp.AppSettings.FormWindowState;

                byte[] layoutBytes = null;
                System.IO.MemoryStream stream = null;
                if (!YiLeSystemApp.AppSettings.IsPanelLayoutNull())
                {
                    layoutBytes = System.Convert.FromBase64String(YiLeSystemApp.AppSettings.PanelLayout);
                    stream = new System.IO.MemoryStream(layoutBytes);
                    this.panelManager.LoadLayoutFile(stream);
                    stream.Close();
                }
                if (!YiLeSystemApp.AppSettings.IsCommandsLayoutNull())
                {
                    layoutBytes = System.Convert.FromBase64String(YiLeSystemApp.AppSettings.CommandsLayout);
                    stream = new System.IO.MemoryStream(layoutBytes);
                    this.ribbon1.LoadLayoutFile(stream);
                    stream.Close();
                }
            }
            BindingContext = new BindingContext();
            CreateVisualStyleColors();
            //Create Commands For AddNew in Folders
            CreateAddNewCommands();
            CreateGoToCommands();
            //set navigator panels in folders
            //to be able to select the correct panel when ApplicationFolder
            //is set in code
            YiLeSystemApp.RootFolder.ContactsFolder.NavigatorPanel = this.uipContacts;
            YiLeSystemApp.RootFolder.CalendarFolder.NavigatorPanel = this.uipCalendar;
            YiLeSystemApp.RootFolder.ProductsAndOrdersFolder.NavigatorPanel = this.uipProductsAndOrders;

            //Fill TreeViews:

            this.SetGridEXTreeProperties(this.treeContacts);
            this.SetGridEXTreeProperties(this.treeProductsAndOrders);
            CreateTreeNode(this.treeContacts, YiLeSystemApp.RootFolder.ContactsFolder);
            CreateTreeNode(this.treeProductsAndOrders, YiLeSystemApp.RootFolder.ProductsAndOrdersFolder);
            selectFolder = false;
            this.treeContacts.Row = 1;
            this.treeProductsAndOrders.Row = 1;
            selectFolder = true;

            if (YiLeSystemApp.ReadSettingsFromDS)
            {
                this.CurrentFolder = YiLeSystemApp.RootFolder.Find(YiLeSystemApp.AppSettings.CurrentFolderName);
            }
            else
            {
                this.CurrentFolder = YiLeSystemApp.RootFolder.ContactsFolder;
            }

            initialized = true;
        }
        private Image CreateColorImage(Color clr, int width, int height)
        {
            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(clr);
            Rectangle r = new Rectangle(0, 0, width - 1, height - 1);
            g.DrawRectangle(Pens.Black, r);
            r.Inflate(-1, -1);
            g.DrawRectangle(Pens.White, r);
            g.Dispose();
            return bmp;
        }
        private void AddCustomColorCommand(Color clr, string name)
        {
            Janus.Windows.Ribbon.GalleryItem item = new Janus.Windows.Ribbon.GalleryItem("COLOR" + name);
            item.Tag = clr;
            item.Image = CreateColorImage(clr, 48, 48);
            this.rgalColors.GalleryItems.Add(item);
        }
        private void CreateBuiltInVisualStyleCommand(string key, string text, Color imageColor)
        {
            Janus.Windows.Ribbon.ButtonCommand command = new Janus.Windows.Ribbon.ButtonCommand(key);
            command.SizeStyle = Janus.Windows.Ribbon.CommandSizeStyle.Large;
            command.ActAsOptionButton = true;
            command.CheckOnClick = true;
            command.Text = text;
            command.Image = CreateColorImage(imageColor, 16, 16);
            command.LargeImage = CreateColorImage(imageColor, 32, 32);
            this.rbngOfficeColors.Commands.Add(command);
        }
        private void CreateVisualStyleColors()
        {
            this.CreateBuiltInVisualStyleCommand("rcmdBlue", "Blue", Color.FromArgb(118, 153, 199));
            this.CreateBuiltInVisualStyleCommand("rcmdSilver", "Silver", Color.Silver);
            this.CreateBuiltInVisualStyleCommand("rcmdBlack", "Black", Color.Black);
            Janus.Windows.Ribbon.ButtonCommand cmdBlue = this.rbngOfficeColors.Commands["rcmdBlue"] as Janus.Windows.Ribbon.ButtonCommand;
            cmdBlue.Checked = true;

            rgalColors.MaxGalleryColumns = 6;


            AddCustomColorCommand(Color.FromArgb(96, 128, 160), "21");
            AddCustomColorCommand(Color.FromArgb(160, 96, 96), "22");
            AddCustomColorCommand(Color.FromArgb(128, 160, 96), "23");
            AddCustomColorCommand(Color.FromArgb(96, 160, 128), "24");
            AddCustomColorCommand(Color.FromArgb(128, 128, 160), "25");
            AddCustomColorCommand(Color.FromArgb(160, 96, 128), "26");

            AddCustomColorCommand(Color.FromArgb(80, 128, 192), "21");
            AddCustomColorCommand(Color.FromArgb(192, 80, 80), "22");
            AddCustomColorCommand(Color.FromArgb(128, 192, 80), "23");
            AddCustomColorCommand(Color.FromArgb(80, 192, 128), "24");
            AddCustomColorCommand(Color.FromArgb(128, 128, 192), "25");
            AddCustomColorCommand(Color.FromArgb(192, 80, 128), "26");

            AddCustomColorCommand(Color.FromArgb(40, 80, 128), "31");
            AddCustomColorCommand(Color.FromArgb(128, 40, 40), "32");
            AddCustomColorCommand(Color.FromArgb(80, 128, 40), "33");
            AddCustomColorCommand(Color.FromArgb(40, 128, 80), "45");
            AddCustomColorCommand(Color.FromArgb(80, 80, 128), "34");
            AddCustomColorCommand(Color.FromArgb(128, 40, 80), "34");

            AddCustomColorCommand(Color.FromArgb(32, 48, 80), "21");
            AddCustomColorCommand(Color.FromArgb(80, 40, 40), "22");
            AddCustomColorCommand(Color.FromArgb(48, 80, 32), "23");
            AddCustomColorCommand(Color.FromArgb(32, 80, 48), "24");
            AddCustomColorCommand(Color.FromArgb(40, 40, 80), "25");
            AddCustomColorCommand(Color.FromArgb(80, 32, 40), "26");

            AddCustomColorCommand(Color.FromArgb(24, 40, 64), "41");
            AddCustomColorCommand(Color.FromArgb(64, 24, 24), "42");
            AddCustomColorCommand(Color.FromArgb(40, 64, 32), "43");
            AddCustomColorCommand(Color.FromArgb(24, 64, 48), "45");
            AddCustomColorCommand(Color.FromArgb(32, 32, 64), "44");
            AddCustomColorCommand(Color.FromArgb(64, 24, 48), "44");


        }
        private void CreateGoToCommands()
        {
            Janus.Windows.Ribbon.SeparatorCommand command = new Janus.Windows.Ribbon.SeparatorCommand();
            command.Title = "Northwind Folders";
            this.ribbon1.ControlBoxMenu.RightCommands.Add(command);
            CreateGoToCommands(YiLeSystemApp.RootFolder.ContactsFolder);
            this.ribbon1.ControlBoxMenu.RightCommands.Add(new Janus.Windows.Ribbon.SeparatorCommand());
            CreateGoToCommand(YiLeSystemApp.RootFolder.CalendarFolder);
            this.ribbon1.ControlBoxMenu.RightCommands.Add(new Janus.Windows.Ribbon.SeparatorCommand());
            CreateGoToCommands(YiLeSystemApp.RootFolder.ProductsAndOrdersFolder);
        }
        private void CreateGoToCommands(ApplicationFolder folder)
        {
            foreach (ApplicationFolder childFolder in folder.Folders)
            {
                CreateGoToCommand(childFolder);
            }
        }
        private void CreateGoToCommand(ApplicationFolder folder)
        {
            Janus.Windows.Ribbon.ButtonCommand command = new Janus.Windows.Ribbon.ButtonCommand(folder.FolderName);
            command.Text = folder.FolderName;
            command.ImageKey = folder.ImageKey;
            command.Tag = folder.FolderName;
            command.Click += new Janus.Windows.Ribbon.CommandEventHandler(this.GoToClick);
            this.ribbon1.ControlBoxMenu.RightCommands.Add(command);
        }
        private void GoToClick(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        {
            ApplicationFolder folder = YiLeSystemApp.RootFolder.Find((String)e.Command.Tag);
            if (folder != null)
            {
                this.Update();
                this.CurrentFolder = folder;
            }
        }

        private void CreateAddNewCommands()
        {
            Janus.Windows.Ribbon.SeparatorCommand sep;
            sep = new Janus.Windows.Ribbon.SeparatorCommand();
            sep.Title = "Contacts";
            this.rcbNew.Commands.Add(sep);
            CreateAddNewCommands(YiLeSystemApp.RootFolder.ContactsFolder);
            sep = new Janus.Windows.Ribbon.SeparatorCommand();
            sep.Title = "Calendar";
            this.rcbNew.Commands.Add(sep);
            CreateAddNewCommand(YiLeSystemApp.RootFolder.CalendarFolder);
            sep = new Janus.Windows.Ribbon.SeparatorCommand();
            sep.Title = "Products And Orders";
            this.rcbNew.Commands.Add(sep); CreateAddNewCommands(YiLeSystemApp.RootFolder.ProductsAndOrdersFolder);
        }
        private void CreateAddNewCommands(ApplicationFolder folder)
        {
            foreach (ApplicationFolder childFolder in folder.Folders)
            {
                if (childFolder.Supports(ApplicationFolder.FolderFeatures.NewItem))
                {
                    CreateAddNewCommand(childFolder);
                }
            }
        }
        private void CreateAddNewCommand(ApplicationFolder folder)
        {
            Janus.Windows.Ribbon.ButtonCommand command;
            command = new Janus.Windows.Ribbon.ButtonCommand("cmdAdd" + folder.FolderName);
            command.ForegroundStyle.FontBold = true;
            command.Description = string.Format("Opens an empty '{0}' Form to enter data for a new element in the '{0}' Folder", folder.FolderName);
            command.SizeStyle = Janus.Windows.Ribbon.CommandSizeStyle.Large;
            string strNewName = folder.FolderName;
            if (strNewName.EndsWith("s"))
            {
                strNewName = strNewName.Substring(0, strNewName.Length - 1);
            }
            command.Text = "New " + strNewName;
            command.LargeImageKey = folder.NewImageKey;
            command.Tag = folder.FolderName;
            command.Click += new Janus.Windows.Ribbon.CommandEventHandler(this.AddNewClick);
            this.rcbNew.Commands.Add(command);
        }
        private void AddNewClick(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        {
            ApplicationFolder folder = YiLeSystemApp.RootFolder.Find((string)e.Command.Tag);
            if (folder != null)
            {
                folder.AddNew();
            }
        }

        public Janus.Windows.Common.VisualStyleManager VisualStyleManager1
        {
            get
            {
                return this.visualStyleManager1;
            }
        }


        private ApplicationFolder mCurrentFolder;
        public ApplicationFolder CurrentFolder
        {
            get
            {
                return mCurrentFolder;
            }
            set
            {
                if (mCurrentFolder != value)
                {
                    if (!this.UpdateCurrentFolder())
                    {
                        return;
                    }
                    System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;
                    if (value != null)
                    {
                        //force the folder to load its data and its content view control
                        value.Load();
                    }

                    if (mCurrentFolder != null)
                    {
                        //remove preview control if it exists
                        this.previewPager.ChildControl = null;
                        //unload current folder
                        mCurrentFolder.Unload();
                    }
                    mCurrentFolder = value;

                    this.OnCurrentFolderChanged();
                    this.ResetStatusBarInfo();
                    System.Windows.Forms.Cursor.Current = Cursors.Default;
                }
            }
        }
        private bool UpdateCurrentFolder()
        {
            //if there is a current folder, try to update its data. 
            //if data can not be updated, cancel the change
            if (this.CurrentFolder != null)
            {
                return this.CurrentFolder.UpdateData();
            }
            else
            {
                return true;
            }
        }
        private void OnCurrentFolderChanged()
        {
            if (mCurrentFolder != null)
            {
                //select navigator panel in case that CurrentFolder is set in code
                if (mCurrentFolder.NavigatorPanel != null)
                {
                    Janus.Windows.GridEX.GridEX treeControl = this.PanelTree(mCurrentFolder.NavigatorPanel);
                    if (treeControl != null)
                    {
                        this.SelectFolderInTree(treeControl, mCurrentFolder);
                    }
                    this.uipNavigator.SelectedPanel = mCurrentFolder.NavigatorPanel;

                }
                this.uipContentGroup.Text = mCurrentFolder.FolderName;
                this.uipContentGroup.ImageKey = mCurrentFolder.ImageKey;
                this.SetViews();
                if (mCurrentFolder.Supports(ApplicationFolder.FolderFeatures.ReadingPane))
                {
                    this.previewPager.MinSize = mCurrentFolder.PreviewControl.FullSize;
                    this.VisualStyleManager1.AddControl(mCurrentFolder.PreviewControl, true);
                    this.previewPager.ChildControl = mCurrentFolder.PreviewControl;
                    mCurrentFolder.PreviewControl.Visible = true;
                }
                this.cmdRecordsEdit.ImageKey = mCurrentFolder.EditImageKey;
                this.cmdRecordsEdit.LargeImageKey = mCurrentFolder.EditImageKey;
                this.cmdRecordsNew.ImageKey = mCurrentFolder.NewImageKey;
            }
            EnableCommands();
        }
        private void EnableCommands()
        {
            if ((mCurrentContentView == null) || !mCurrentContentView.Printable)
            {
                this.rcmdPrint.Enabled = false;
                this.rcmdPrintPreview.Enabled = false;
            }
            else
            {
                this.rcmdPrint.Enabled = true;
                this.rcmdPrintPreview.Enabled = true;
            }
            if (this.CurrentFolder != null && this.mCurrentFolder.Supports(ApplicationFolder.FolderFeatures.ReadingPane))
            {
                this.rbngReadingPane.Visible = true;
                this.rcmdReadingPaneRight.Enabled = true;
                this.rcmdReadingPaneOff.Enabled = true;
                this.rcmdReadingPaneBottom.Enabled = true;
                switch (this.CurrentFolder.CurrentView.ReadingPaneLocation)
                {
                    case ReadingPaneLocation.Off:
                        this.rcmdReadingPaneOff.Checked = true;
                        break;
                    case ReadingPaneLocation.Bottom:
                        this.rcmdReadingPaneBottom.Checked = true;
                        break;
                    case ReadingPaneLocation.Right:
                        this.rcmdReadingPaneRight.Checked = true;
                        break;
                }
            }
            else
            {
                this.rbngReadingPane.Visible = false;
                this.rcmdReadingPaneRight.Enabled = false;
                this.rcmdReadingPaneOff.Enabled = false;
                this.rcmdReadingPaneBottom.Enabled = false;
            }
            if (mCurrentContentView != null)
            {
                this.cmdRecordsDelete.Enabled = (this.mCurrentContentView.CanDelete);
                this.cmdRecordsEdit.Enabled = (this.mCurrentContentView.CanEdit);

            }
            else
            {
                this.cmdRecordsEdit.Enabled = false;
                this.cmdRecordsDelete.Enabled = false;
            }
            if (mCurrentFolder != null)
            {
                this.cmdRecordsNew.Enabled = mCurrentFolder.CanAdd;
            }
            else
            {
                this.cmdRecordsNew.Enabled = false;
            }

        }
        private ContentViewControl mCurrentContentView;
        private void ShowCurrentFolderView()
        {
            if (mCurrentFolder != null)
            {
                ContentViewControl ctl = mCurrentFolder.CurrentContentView;
                if (ctl != null)
                {
                    ctl.FolderView = mCurrentFolder.CurrentView;
                    if (ctl is ScheduleView)
                    {
                        //bind the date selector to the schedule in the view
                        this.dateSelector.Schedule = ((ScheduleView)ctl).Schedule;
                        this.ScheduleOwnersList.DataSource = ((ScheduleView)ctl).Schedule.Owners;

                    }
                    CurrentContentView = ctl;

                    mCurrentContentView.Focus();
                    switch (mCurrentFolder.CurrentView.ReadingPaneLocation)
                    {
                        case ReadingPaneLocation.Off:
                            this.uipContentPreview.Closed = true;
                            break;
                        case ReadingPaneLocation.Right:
                            this.uipContentGroup.GroupStyle = PanelGroupStyle.VerticalTiles;
                            this.uipContentPreview.Closed = false;
                            break;
                        case ReadingPaneLocation.Bottom:
                            this.uipContentGroup.GroupStyle = PanelGroupStyle.HorizontalTiles;
                            this.uipContentPreview.Closed = false;
                            break;
                    }
                    if (mCurrentFolder.Supports(ApplicationFolder.FolderFeatures.ReadingPane))
                    {
                        mCurrentFolder.PreviewControl.BindingContext = mCurrentContentView.BindingContext;
                        mCurrentFolder.PreviewControl.DataSource = mCurrentContentView.DataSource;
                        //mCurrentFolder.PreviewControl.AllowEdit = false;
                        this.previewPager.ChildControl = mCurrentFolder.PreviewControl;

                    }
                }
                else
                {
                    CurrentContentView = null;
                }
            }
            ResetStatusBarInfo();
            EnableCommands();
        }
        public void ResetStatusBarInfo()
        {
            if ((mCurrentContentView == null))
            {
                this.sbInfoText.Text = "";
            }
            else
            {

                this.sbInfoText.Text = mCurrentContentView.StatusBarInfo;
            }
            this.sbDate.Text = System.DateTime.Today.ToString("d");
        }
        public ContentViewControl CurrentContentView
        {
            get
            {
                return mCurrentContentView;
            }
            set
            {
                if (mCurrentContentView != value)
                {
                    if (mCurrentContentView != null)
                    {
                        //force CurrentContentView to save its settings
                        mCurrentContentView.SaveSettings();
                        this.ribbon1.UnmergeRibbon();
                        this.uipContentContainer.Controls.Remove(mCurrentContentView);
                        mCurrentContentView.CurrentItemChanged -= new EventHandler(this.CurrentItemChanged);
                    }
                    mCurrentContentView = value;
                    if (mCurrentContentView != null)
                    {
                        mCurrentContentView.Dock = DockStyle.Fill;
                        mCurrentContentView.Bounds = this.uipContentContainer.ClientRectangle;
                        mCurrentContentView.Visible = false;
                        this.uipContentContainer.Controls.Add(mCurrentContentView);
                        this.VisualStyleManager1.AddControl(mCurrentContentView, true);
                        if (mCurrentContentView.RibbonControl != null)
                        {
                            this.ribbon1.MergeRibbon(this.mCurrentContentView.RibbonControl);
                        }
                        mCurrentContentView.Visible = true;
                        this.OnCurrentItemChanged();
                        mCurrentContentView.CurrentItemChanged += new EventHandler(this.CurrentItemChanged);

                    }
                    this.EnableCommands();

                }
            }
        }
        private void OnCurrentItemChanged()
        {

            if (this.CurrentContentView != null & this.CurrentContentView.CurrentItem != null)
            {
                this.previewPager.Visible = true;
            }
            else
            {
                this.previewPager.Visible = false;
            }
            if (CurrentContentView != null)
            {
                this.cmdRecordsDelete.Enabled = CurrentContentView.CanDelete;
                this.cmdRecordsEdit.Enabled = CurrentContentView.CanEdit;
            }


        }
        private void CurrentItemChanged(object sender, EventArgs e)
        {
            OnCurrentItemChanged();
        }
        private void SetViews()
        {
            UIPanel viewsPanel = null;
            if (this.uipNavigator.SelectedPanel == this.uipContacts)
            {
                viewsPanel = this.uipContactFolderView;
            }
            else if (this.uipNavigator.SelectedPanel == this.uipProductsAndOrders)
            {
                viewsPanel = this.uipProdAndOrdersViews;
            }
            if (viewsPanel != null)
            {
                if (mCurrentFolder.Supports(ApplicationFolder.FolderFeatures.MultipleViews))
                {
                    Janus.Windows.EditControls.UIRadioButton optionButton = null;
                    int buttonTop = 4;
                    viewsPanel.InnerContainer.Controls.Clear();
                    UIPager optionsPager = new UIPager();
                    optionsPager.Dock = DockStyle.Fill;
                    optionsPager.VisualStyleManager = this.VisualStyleManager1;
                    Janus.Windows.EditControls.UIGroupBox gBox = new Janus.Windows.EditControls.UIGroupBox();
                    gBox.BackgroundStyle = Janus.Windows.EditControls.BackgroundStyle.Default;
                    gBox.BackColor = SystemColors.Window;
                    gBox.BorderColor = Color.Transparent;
                    gBox.Height = 0;
                    //viewsPanel.InnerContainer.AutoScroll = true;
                    foreach (FolderView folderView in mCurrentFolder.Views)
                    {

                        optionButton = this.CreateOptionForView(folderView, viewsPanel.InnerContainer.Width);
                        //Select default view
                        if (folderView == mCurrentFolder.CurrentView)
                        {
                            optionButton.Checked = true;
                        }
                        optionButton.Location = new Point(8, buttonTop);
                        buttonTop = buttonTop + optionButton.Height;
                        optionButton.CheckedChanged += new EventHandler(this.ViewOption_CheckedChanged);
                        gBox.Controls.Add(optionButton);
                    }
                    gBox.Height = optionButton.Bounds.Bottom;
                    gBox.Width = viewsPanel.InnerContainer.Width;
                    optionsPager.MinSize = new Size(0, gBox.Height);
                    optionsPager.ScrollMode = ScrollMode.Vertical;
                    optionsPager.ChildControl = gBox;
                    viewsPanel.InnerContainer.Controls.Add(optionsPager);
                    viewsPanel.Closed = false;

                }
                else
                {
                    viewsPanel.Closed = true;
                }
                this.VisualStyleManager1.AddControl(viewsPanel, true);

            }

            ShowCurrentFolderView();
        }
        private void ViewOption_CheckedChanged(object sender, EventArgs e)
        {
            Janus.Windows.EditControls.UIRadioButton optChanged = null;
            optChanged = (Janus.Windows.EditControls.UIRadioButton)sender;
            if (optChanged.Checked)
            {
                mCurrentFolder.CurrentView = (FolderView)optChanged.Tag;
                ShowCurrentFolderView();
            }
        }

        private void SelectFolderInTree(Janus.Windows.GridEX.GridEX tree, ApplicationFolder folder)
        {
            Janus.Windows.GridEX.GridEXRow row = null;
            row = tree.GetRow(folder);
            if (row != null)
            {
                tree.MoveTo(row);
            }
        }

        private Janus.Windows.GridEX.GridEX PanelTree(UIPanelBase panel)
        {
            if (panel.Name == this.uipContacts.Name)
            {
                return this.treeContacts;
            }
            else if (panel.Name == this.uipProductsAndOrders.Name)
            {
                return this.treeProductsAndOrders;
            }
            else
            {
                return null;
            }
        }

        private void OnContactsPanelSelected()
        {
            if (this.treeContacts.Row < 0)
            {
                if (this.treeContacts.RowCount >= 1)
                {
                    this.treeContacts.Row = 1;
                }
            }
            else
            {
                this.CurrentFolder = (ApplicationFolder)(this.treeContacts.GetRow().DataRow);
            }
        }
        private void OnProductsAndOrdersPanelSelected()
        {
            if (this.treeProductsAndOrders.Row < 0)
            {
                if (this.treeProductsAndOrders.RowCount >= 1)
                {
                    this.treeProductsAndOrders.Row = 1;
                }
            }
            else
            {
                this.CurrentFolder = (ApplicationFolder)(this.treeProductsAndOrders.GetRow().DataRow);
            }

        }
        private void OnCalendarPanelSelected()
        {
            //this.CurrentFolder = YiLeSystemApp.RootFolder.CalendarFolder;
        }





        private void tree_CurrentCellChanging(object sender, Janus.Windows.GridEX.CurrentCellChangingEventArgs e)
        {
            if (!this.UpdateCurrentFolder())
            {
                e.Cancel = true;
            }
        }

        private void Tree_CurrentCellChanged(object sender, EventArgs e)
        {
            Janus.Windows.GridEX.GridEX tree = null;
            tree = (Janus.Windows.GridEX.GridEX)sender;
            if (!this.uipNavigator.SelectedPanel.Contains(tree))
            {
                return;
            }
            Janus.Windows.GridEX.GridEXRow currentRow = null;
            currentRow = tree.GetRow();
            if (currentRow != null)
            {
                CurrentFolder = (ApplicationFolder)currentRow.DataRow;
            }

        }





        internal Janus.Windows.UI.Dock.UIPanelInnerContainer uipCalendarDateSelectorContainer;
        internal Janus.Windows.UI.Dock.UIPanel uipCalendarDateSelector;
        internal Janus.Windows.Schedule.Calendar dateSelector;
        internal Janus.Windows.UI.Dock.UIPager previewPager;



        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.VisualStyleManager1.AddControl(this, true);
            //Calendar folder must be loaded all the time to be able to
            //show reminders even when another folder is visible.
            //besides, to edit an appointment the schedule control that
            //owns the appointment must be loaded in order to save that appointment
            //correctly when the appointment is recurrent.
            //YiLeSystemApp.YiLeSystemApplication.LoadCalendar();

        }
        private void RemoveRibbonDynamicCommands()
        {
            this.rbngOfficeColors.Commands.Clear();
            this.rgalColors.GalleryItems.Clear();
            this.rcbNew.Commands.Clear();
            this.ribbon1.ControlBoxMenu.RightCommands.Clear();
        }
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (!this.UpdateCurrentFolder())
            {
                e.Cancel = true;
                return;
            }
            YiLeSystemApp.AppSettings.BeginEdit();
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            this.panelManager.SaveLayoutFile(stream);
            YiLeSystemApp.AppSettings.PanelLayout = System.Convert.ToBase64String(stream.ToArray());
            stream.Close();

            stream = new System.IO.MemoryStream();
            //First remove the ribbon commands that are created in code.
            RemoveRibbonDynamicCommands();
            this.ribbon1.SaveLayoutFile(stream);
            YiLeSystemApp.AppSettings.CommandsLayout = System.Convert.ToBase64String(stream.ToArray());
            stream.Close();

            if (this.WindowState == FormWindowState.Normal)
            {
                YiLeSystemApp.AppSettings.FormLeft = this.Left;
                YiLeSystemApp.AppSettings.FormTop = this.Top;
                YiLeSystemApp.AppSettings.FormWidth = this.Width;
                YiLeSystemApp.AppSettings.FormHeight = this.Height;
            }
            YiLeSystemApp.AppSettings.FormWindowState = (int)this.WindowState;
            YiLeSystemApp.AppSettings.CurrentFolderName = this.CurrentFolder.FolderName;
            YiLeSystemApp.SaveAppSettings();
            this.CurrentContentView = null;
            base.OnClosing(e);
        }

        private Janus.Windows.EditControls.UIRadioButton CreateOptionForView(FolderView view, int width)
        {
            Janus.Windows.EditControls.UIRadioButton viewControl = new Janus.Windows.EditControls.UIRadioButton();

            viewControl.Text = view.ViewName;
            viewControl.Tag = view;
            viewControl.BackColor = Color.Transparent;
            viewControl.VisualStyleManager = this.VisualStyleManager1;

            viewControl.WordWrap = false;
            viewControl.Size = new Size(width - 15, this.Font.Height + 4);
            viewControl.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            return viewControl;
        }

        private void CreateTreeNode(Janus.Windows.GridEX.GridEX grid, ApplicationFolder folder)
        {

            grid.DataSource = new ApplicationFolder[] { folder };
            grid.ExpandRecords();


        }

        private void panelManager_GroupSelectedPanelChanging(object sender, Janus.Windows.UI.Dock.GroupSelectedPanelChangingEventArgs e)
        {
            e.Cancel = !this.UpdateCurrentFolder();
        }

        private void panelManager_PanelClosedChanged(object sender, Janus.Windows.UI.Dock.PanelActionEventArgs e)
        {
            //TODO
            //if (e.Panel == this.uipNavigator)
            //{
            //    this.cmdViewNavigationPane1.IsChecked = ! e.Panel.Closed;
            //}
        }

        private void ScheduleOwnersList_SelectionChanged(object sender, System.EventArgs e)
        {
            Janus.Windows.GridEX.GridEXRow currentRow = null;
            currentRow = this.ScheduleOwnersList.GetRow();
            if (currentRow != null)
            {
                //set the selected row as the current owner in the schedule
                if (this.CurrentContentView is ScheduleView)
                {
                    Janus.Windows.Schedule.ScheduleAppointmentOwner owner = null;
                    owner = (Janus.Windows.Schedule.ScheduleAppointmentOwner)currentRow.DataRow;
                    ((ScheduleView)this.CurrentContentView).Schedule.CurrentOwner = owner;
                }
            }
        }
        private void ScheduleOwnersList_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            Janus.Windows.GridEX.GridEXRow currentRow = null;
            int rowClicked = 0;
            rowClicked = this.ScheduleOwnersList.RowPositionFromPoint(e.X, e.Y);
            if (rowClicked >= 0)
            {
                currentRow = this.ScheduleOwnersList.GetRow(rowClicked);
                if (currentRow != null)
                {
                    Janus.Windows.Schedule.ScheduleAppointmentOwner owner = null;
                    owner = (Janus.Windows.Schedule.ScheduleAppointmentOwner)currentRow.DataRow;
                    try
                    {
                        owner.Visible = !owner.Visible;
                        this.ScheduleOwnersList.Refresh();
                    }
                    catch
                    {
                        //an exception may occur if we try to hide current owner
                    }
                }
            }
        }
        internal Janus.Windows.Ribbon.RibbonStatusBar uisbMainForm;

        //private void tbStandard_CommandClick(object sender, Janus.Windows.UI.CommandBars.CommandEventArgs e)
        //{
        //    this.VisualStyleManager1.AddControl(this, true);

        //}

        private void MainForm_Load(object sender, System.EventArgs e)
        {

            this.VisualStyleManager1.DefaultColorScheme = "";
            this.VisualStyleManager1.ColorSchemes.Clear();
            Janus.Windows.Common.JanusColorScheme cs = null;

            cs = new Janus.Windows.Common.JanusColorScheme("Default");
            cs.VisualStyle = Janus.Windows.Common.VisualStyle.Office2010;
            cs.UseThemes = true;
            cs.OfficeColorScheme = Janus.Windows.Common.OfficeColorScheme.Default;
            Janus.Windows.Common.VisualStyleManager.DefaultOfficeColorScheme = Janus.Windows.Common.OfficeColorScheme.Blue;

            this.VisualStyleManager1.ColorSchemes.Add(cs);
            this.VisualStyleManager1.DefaultColorScheme = "Default";


        }

        private void SetGridEXTreeProperties(Janus.Windows.GridEX.GridEX grid)
        {
            grid.BorderStyle = Janus.Windows.GridEX.BorderStyle.None;
            grid.AllowEdit = Janus.Windows.GridEX.InheritableBoolean.False;
            grid.HideSelection = Janus.Windows.GridEX.HideSelection.HighlightInactive;
            grid.KeepRowSettings = true;
            grid.RootTable = new Janus.Windows.GridEX.GridEXTable();
            grid.SelectOnExpand = true;
            grid.ColumnAutoResize = true;
            grid.GridLines = Janus.Windows.GridEX.GridLines.None;
            grid.GroupByBoxVisible = false;
            grid.ColumnHeaders = Janus.Windows.GridEX.InheritableBoolean.False;
            grid.FocusStyle = Janus.Windows.GridEX.FocusStyle.None;
            grid.RootTable.HierarchicalMode = Janus.Windows.GridEX.HierarchicalMode.SelfReferencingChildList;
            Janus.Windows.GridEX.GridEXColumn col = null;
            col = grid.RootTable.Columns.Add("FolderName", Janus.Windows.GridEX.ColumnType.ImageAndText);
            col.Selectable = false;
            grid.RootTable.SelfReferencingSettings.ExpandColumn = col;
            grid.RootTable.SelfReferencingSettings.AutoSizeColumnOnExpand = true;
            grid.RootTable.SelfReferencingSettings.ChildListMember = "Folders";

        }
        protected override void OnCreateControl()
        {
            base.OnCreateControl();
        }

        private void tree_FormattingRow(object sender, Janus.Windows.GridEX.RowLoadEventArgs e)
        {
            if (e.Row.RowType == Janus.Windows.GridEX.RowType.Record)
            {
                ApplicationFolder folder = (ApplicationFolder)e.Row.DataRow;
                e.Row.Cells["FolderName"].ImageKey = folder.ImageKey;
            }
        }
        private void UncheckCustomColors()
        {
            foreach (Janus.Windows.Ribbon.GalleryItem item in this.rgalColors.GalleryItems)
            {
                item.Checked = false;
            }
        }
        private void ribbon1_CommandClick(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        {
            if (e.Command.Key.StartsWith("COLOR"))
            {
                Janus.Windows.Common.VisualStyleManager.DefaultOfficeColorScheme = Janus.Windows.Common.OfficeColorScheme.Custom;
                Janus.Windows.Common.VisualStyleManager.DefaultOfficeCustomColor = (Color)e.Command.Tag;
                foreach (Janus.Windows.Ribbon.ButtonCommand btnCommand in this.rbngOfficeColors.Commands)
                {
                    btnCommand.Checked = false;
                }
            }
            else if (e.Command.Tag is FolderView)
            {
                mCurrentFolder.CurrentView = (FolderView)e.Command.Tag;
                ShowCurrentFolderView();
            }
            else
            {
                switch (e.Command.Key)
                {
                    case "rcmdBlack":
                        Janus.Windows.Common.VisualStyleManager.DefaultOfficeColorScheme = Janus.Windows.Common.OfficeColorScheme.Black;
                        UncheckCustomColors();
                        break;
                    case "rcmdBlue":
                        Janus.Windows.Common.VisualStyleManager.DefaultOfficeColorScheme = Janus.Windows.Common.OfficeColorScheme.Blue;
                        UncheckCustomColors();
                        break;
                    case "rcmdSilver":
                        Janus.Windows.Common.VisualStyleManager.DefaultOfficeColorScheme = Janus.Windows.Common.OfficeColorScheme.Silver;
                        UncheckCustomColors();
                        break;
                    case "cmdRecordsEdit":
                        if (mCurrentContentView != null)
                        {
                            mCurrentContentView.Edit();
                        }
                        break;
                    case "rcbPrintPreview":
                    case "rcmdPrintPreview":
                        if (mCurrentContentView != null)
                        {
                            mCurrentContentView.PrintPreview(this);
                        }
                        break;
                    case "rcbPrint":
                    case "rcmdPrint":
                        if (mCurrentContentView != null)
                        {
                            mCurrentContentView.Print();
                        }
                        break;
                    case "rcbClose":
                    case "cbExit":
                        this.Close();
                        break;
                    case "cmdRecordsNew":
                        if (mCurrentFolder != null)
                        {
                            mCurrentFolder.AddNew();
                        }
                        break;
                    case "cmdRecordsDelete":
                        if (mCurrentContentView != null)
                        {
                            mCurrentContentView.Delete();
                        }
                        break;
                    case "rcmdReadingPaneRight":
                        this.CurrentFolder.CurrentView.ReadingPaneLocation = ReadingPaneLocation.Right;
                        this.uipContentGroup.GroupStyle = PanelGroupStyle.VerticalTiles;
                        this.uipContentPreview.Closed = false;
                        break;
                    case "rcmdReadingPaneBottom":
                        this.CurrentFolder.CurrentView.ReadingPaneLocation = ReadingPaneLocation.Bottom;
                        this.uipContentGroup.GroupStyle = PanelGroupStyle.HorizontalTiles;
                        this.uipContentPreview.Closed = false;
                        break;
                    case "rcmdReadingPaneOff":
                        this.CurrentFolder.CurrentView.ReadingPaneLocation = ReadingPaneLocation.Off;
                        this.uipContentPreview.Closed = true;
                        break;
                }
            }
            //    switch (e.Command.Key)
            //    {
            //        case "cdmViewNavigationPane":
            //            this.uipNavigator.Closed = !this.uipNavigator.Closed;
            //            break;

            //        case "cmdPrintPreview":
            //            if (mCurrentContentView != null)
            //            {
            //                mCurrentContentView.PrintPreview(this);
            //            }
            //            break;
            //        case "cmdPrint":
            //            if (mCurrentContentView != null)
            //            {
            //                mCurrentContentView.Print();
            //            }
            //            break;
            //        case "cmdDelete":
            //            if (mCurrentContentView != null)
            //            {
            //                mCurrentContentView.Delete();
            //            }
            //            break;
            //        case "cmdEdit":
            //            if (mCurrentContentView != null)
            //            {
            //                mCurrentContentView.Edit();
            //            }
            //            break;
            //        case "cmdViewStandard":
            //            this.tbStandard.Visible = !this.tbStandard.Visible;
            //            this.cmdViewStandard.IsChecked = this.tbStandard.Visible;
            //            break;
            //        case "cmdViewStatusBar":
            //            this.uisbMainForm.Visible = !this.uisbMainForm.Visible;
            //            this.cmdViewStatusBar.IsChecked = !this.cmdViewStatusBar.IsChecked;
            //            break;
            //        case "cmdQuickReadingPane":
            //            this.cmdQuickReadingPane.IsChecked = !this.cmdQuickReadingPane.IsChecked;
            //            this.uipContentPreview.Closed = !this.cmdQuickReadingPane.IsChecked;
            //            break;
            //        case "cmdCustomize":
            //            this.commandManager.ShowCustomizeDialog();
            //            break;
            //        case "cmdAbout":
            //            frmAbout frm = new frmAbout();
            //            frm.ShowDialog(this);
            //            frm.Dispose();
            //            break;
        }

        private void btnNewCustomer_Click(object sender, EventArgs e)
        {
            ApplicationFolder folder = YiLeSystemApp.RootFolder.Find("Customers");
            if (folder != null)
            {
                folder.AddNew();
            }
        }

        private void btnNewSupplier_Click(object sender, EventArgs e)
        {
            ApplicationFolder folder = YiLeSystemApp.RootFolder.Find("Suppliers");
            if (folder != null)
            {
                folder.AddNew();
            }
        }

        private void btnNewEmployee_Click(object sender, EventArgs e)
        {
            ApplicationFolder folder = YiLeSystemApp.RootFolder.Find("Employees");
            if (folder != null)
            {
                folder.AddNew();
            }
        }

        private void bsbClose_Click(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        {
            this.Close();
        }

        private void btnNewAppointment_Click(object sender, EventArgs e)
        {
            ApplicationFolder folder = YiLeSystemApp.RootFolder.Find("Calendar");
            if (folder != null)
            {
                folder.AddNew();
            }
        }

        private void btnNewProduct_Click(object sender, EventArgs e)
        {
            ApplicationFolder folder = YiLeSystemApp.RootFolder.Find("Products");
            if (folder != null)
            {
                folder.AddNew();
            }
        }

        private void btnNewOrder_Click(object sender, EventArgs e)
        {
            ApplicationFolder folder = YiLeSystemApp.RootFolder.Find("Orders");
            if (folder != null)
            {
                folder.AddNew();
            }
        }

    }

} //end of root namespace
